package org.myorg.myviewer;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Logger;
import org.myorg.myapi.APIObject;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

//import org.openide.util.Utilities;
/**
 * Top component which displays something.
 */
final class MyViewerTopComponent extends TopComponent implements LookupListener {

    private static MyViewerTopComponent instance;
    /** path to the icon used by the component and its open action */
    //    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "MyViewerTopComponent";

    private Lookup.Result result = null;

    private MyViewerTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(MyViewerTopComponent.class, "CTL_MyViewerTopComponent"));
        setToolTipText(NbBundle.getMessage(MyViewerTopComponent.class, "HINT_MyViewerTopComponent"));
        //        setIcon(Utilities.loadImage(ICON_PATH, true));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "[nothing selected]");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "jLabel2");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(jLabel2))
                .addContainerGap(163, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel2)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
            // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration//GEN-END:variables
    // End of variables declaration
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized MyViewerTopComponent getDefault() {
        if (instance == null) {
            instance = new MyViewerTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the MyViewerTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized MyViewerTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(MyViewerTopComponent.class.getName()).warning("Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof MyViewerTopComponent) {
            return (MyViewerTopComponent) win;
        }
        Logger.getLogger(MyViewerTopComponent.class.getName()).warning("There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public void componentOpened() {
        @SuppressWarnings(value = "unchecked")
        Lookup.Template tpl = new Lookup.Template(APIObject.class);
        result = Utilities.actionsGlobalContext().lookup(tpl);
        result.addLookupListener(this);
    }

    @Override
    public void componentClosed() {
        result.removeLookupListener(this);
        result = null;
    }

    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    protected String preferredID() {
        return PREFERRED_ID;
    }

    static final class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return MyViewerTopComponent.getDefault();
        }
    }

    public void resultChanged(LookupEvent lookupEvent) {
        Lookup.Result r = (Lookup.Result) lookupEvent.getSource();
        Collection c = r.allInstances();
        if (!c.isEmpty()) {
            StringBuffer text1 = new StringBuffer();
            StringBuffer text2 = new StringBuffer();
            for (Iterator i = c.iterator(); i.hasNext();) {
                APIObject o = (APIObject) i.next();
                text1.append(o.getIndex());
                text2.append(o.getDate().toString());
                if (i.hasNext()) {
                    text1.append(',');
                    text2.append(',');
                }
            }
            jLabel1.setText(text1.toString());
            jLabel2.setText(text2.toString());  
        } else {
            jLabel1.setText("[no selection]");
            jLabel2.setText("");
        }
    }
}
